package com.yupi.springbootinit.service;

import java.time.Instant;
import java.time.format.DateTimeFormatter;

/**
 * 工具：与 Influx2 无关的通用解析工具
 */
public class InfluxResultParser {

    private static final DateTimeFormatter ISO = DateTimeFormatter.ISO_INSTANT;

    public static String toIsoTime(Object timeVal) {
        if (timeVal == null) return null;
        if (timeVal instanceof String) {
            return (String) timeVal;
        }
        if (timeVal instanceof Number) {
            long epochMs = ((Number) timeVal).longValue();
            return ISO.format(Instant.ofEpochMilli(epochMs));
        }
        return String.valueOf(timeVal);
    }

    public static Double toDouble(Object v) {
        if (v == null) return null;
        if (v instanceof Number) return ((Number) v).doubleValue();
        try {
            return Double.parseDouble(String.valueOf(v));
        } catch (Exception e) {
            return null;
        }
    }

    public static Integer toInteger(Object v) {
        if (v == null) return null;
        if (v instanceof Number) return ((Number) v).intValue();
        try {
            return Integer.parseInt(String.valueOf(v));
        } catch (Exception e) {
            return null;
        }
    }

    public static Boolean toBoolean(Object v) {
        if (v == null) return null;
        if (v instanceof Boolean) return (Boolean) v;
        if (v instanceof Number) return ((Number) v).intValue() != 0;
        String s = String.valueOf(v);
        if ("true".equalsIgnoreCase(s)) return true;
        if ("false".equalsIgnoreCase(s)) return false;
        return null;
    }
}